/*Copyright (C) 2009 - 2010 MASSART GAUTHIER

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <process.h>
#include <unistd.h>

/* Permet de copier un fichier.
*/
int fichier_cpy(const char *dest_filename, const char *orig_filename) {
	FILE *dest_file = NULL, *orig_file = NULL;
	char buffer[1024];
	size_t nb_bytes_read;

	orig_file = fopen(orig_filename, "rb");
	if(orig_file == NULL) {
		return 1;
	}
	dest_file = fopen(dest_filename, "wb+");
	if(dest_file == NULL) {
		fclose(orig_file);
		return 1;
	}

	do {
		nb_bytes_read = fread(buffer, sizeof(char), 1024, orig_file);

		if(nb_bytes_read > 0) {
			fwrite(buffer, sizeof(char), nb_bytes_read, dest_file);
		}
	}
	while(!feof(orig_file) && !ferror(orig_file) && !ferror(dest_file));

	if(!feof(orig_file)) {
		fclose(orig_file);
		fclose(dest_file);
		return 1;
	}

	fclose(orig_file);
	fclose(dest_file);
	return 0;
}

/* Vérifie la présence d'un fichier.
*/
int fichier_existe(const char *filename) {
	FILE *file;

	file = fopen(filename, "r");

	if(file != NULL) {
		fclose(file);
		return 1;
	}

	return 0;
}

int main(int argc, char *argv[]) {
#ifdef WIN32
	char fichier_maj[] = "[MAJ]Les Jeux Indemodables.exe", fichier_original[] = "Les Jeux Indemodables.exe";
	system("title Mise a jour...");
	system("mode con cols=60 lines=6");
#else
	char fichier_maj[] = "[MAJ]Les Jeux Indemodables",fichier_original[] = "Les Jeux Indemodables";
#endif
	printf("-Verification de la presence du fichier de mise a jour :\n");
	if(fichier_existe(fichier_maj)) {
		printf(" -Fichier present.\n");
		printf("-Copie de la nouvelle version :\n");
		if(!fichier_cpy(fichier_original, fichier_maj)) {
			printf(" -Fichier copie\n");
		}
		else {
			printf(" -Echec de copie du nouveau fichier\n\n");
			printf("\tAppuyer sur une touche pour continuer\n");
			getchar();
		}
	}
	else {
		printf(" -Fichier inexistant.\n\n");
		printf("\tAppuyer sur une touche pour continuer\n");
		getchar();
	}

	printf("-Redemarage du jeu.\n");
	execv(fichier_original, argv);
	return 0;
}
